﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Itfort.Tasks
{
	/// <summary>
	/// 任务服务。
	/// </summary>
	public class TaskService
	{
		static Thread _MainThread;
		static Thread _MonitorThread;
		static Dictionary<string, TaskRunner> m_taskRunners = new Dictionary<string, TaskRunner>();

		/// <summary>
		/// 开启任务服务。
		/// </summary>
		public static void Run()
		{
			if (_MainThread != null || _MonitorThread != null)
			{
				throw new InvalidOperationException("任务服务已被调用，请勿重复调用。");
			}

			_MainThread = new Thread(MainStart);
			_MonitorThread = new Thread(MonitorStart);
			_MainThread.Start();
			_MonitorThread.Start();
		}

		/// <summary>
		/// 任务执行方法。
		/// 以常驻线程方式运行该方法。
		/// </summary>
		static void MainStart()
		{
			while (true)
			{
				try
				{
					var taskRunners = GetTaskRunners();
					foreach (var taskRunner in taskRunners)
					{
						try
						{
							if (taskRunner.CanRun())
							{
								taskRunner.Run();
							}
						}
						catch
						{

						}
					}
				}
				catch
				{

				}

				Thread.Sleep(1000);
			}
		}

		/// <summary>
		/// 状态监视方法。
		/// 以常驻线程方式运行该方法。
		/// </summary>
		static void MonitorStart()
		{
			while (true)
			{
				Thread.Sleep(5000);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="taskRunner"></param>
		public static void AddTaskRunner(TaskRunner taskRunner)
		{
			var taskName = taskRunner.Name.ToUpper();
			if (!m_taskRunners.ContainsKey(taskName))
			{
				m_taskRunners.Add(taskName, taskRunner);
			}
			else
			{

			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="taskName"></param>
		public static void RemoveTaskRunner(string taskName)
		{
			taskName = taskName.ToUpper();
			if (m_taskRunners.ContainsKey(taskName))
			{
				m_taskRunners.Remove(taskName);
			}
			else
			{

			}
		}

		static TaskRunner[] GetTaskRunners()
		{
			return m_taskRunners.Select(p => p.Value).ToArray();
		}
	}
}
